{% extends "base.html" %}

{% block title %}情感分析 - {{ super() }}{% endblock %}

{% block extra_css %}
<!-- 统一设计系统 -->
<link rel="stylesheet" href="/static/css/design-system/index.css">
<!-- 页面特定样式 -->
<style>
    /* 页面布局 */
    .sentiment-page {
        background-color: var(--color-bg-tertiary);
    }

    /* 内容区域 */
    .content-area {
        max-width: 1600px;
        margin: 0 auto;
    }

    /* 页面标题区域 */
    .page-header {
        background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);
        color: white;
        padding: var(--spacing-8) 0;
        margin-bottom: var(--spacing-6);
        border-radius: var(--radius-lg);
        box-shadow: var(--shadow-lg);
    }

    .page-title {
        font-size: var(--font-size-3xl);
        font-weight: var(--font-weight-bold);
        margin-bottom: var(--spacing-2);
    }

    .page-subtitle {
        font-size: var(--font-size-lg);
        opacity: 0.9;
    }

        /* 统计卡片区域 */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: var(--spacing-6);
            margin-bottom: var(--spacing-8);
        }

        .stat-card-enhanced {
            background: white;
            border-radius: var(--radius-lg);
            padding: var(--spacing-6);
            box-shadow: var(--shadow-md);
            border-left: 4px solid #8b5cf6;
            transition: all var(--transition-normal) var(--ease-in-out);
            position: relative;
            overflow: hidden;
        }

        .stat-card-enhanced::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 100px;
            height: 100px;
            background: radial-gradient(circle, rgba(139, 92, 246, 0.1) 0%, transparent 70%);
            border-radius: 50%;
        }

        .stat-card-enhanced:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-lg);
        }

        .stat-card-enhanced.positive {
            border-left-color: var(--color-success);
        }

        .stat-card-enhanced.positive::before {
            background: radial-gradient(circle, rgba(34, 197, 94, 0.1) 0%, transparent 70%);
        }

        .stat-card-enhanced.negative {
            border-left-color: var(--color-error);
        }

        .stat-card-enhanced.negative::before {
            background: radial-gradient(circle, rgba(239, 68, 68, 0.1) 0%, transparent 70%);
        }

        .stat-card-enhanced.neutral {
            border-left-color: var(--color-info);
        }

        .stat-card-enhanced.neutral::before {
            background: radial-gradient(circle, rgba(59, 130, 246, 0.1) 0%, transparent 70%);
        }

        .stat-value {
            font-size: var(--font-size-3xl);
            font-weight: var(--font-weight-bold);
            color: var(--color-text-primary);
            margin-bottom: var(--spacing-1);
        }

        .stat-label {
            color: var(--color-text-secondary);
            font-size: var(--font-size-sm);
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }

        /* 筛选面板 */
        .filter-section {
            background: white;
            border-radius: var(--radius-lg);
            padding: var(--spacing-6);
            margin-bottom: var(--spacing-8);
            box-shadow: var(--shadow-md);
        }

        .filter-title {
            font-size: var(--font-size-lg);
            font-weight: var(--font-weight-semibold);
            margin-bottom: var(--spacing-4);
            color: var(--color-text-primary);
        }

        .filter-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: var(--spacing-4);
            margin-bottom: var(--spacing-4);
        }

        .filter-actions {
            display: flex;
            gap: var(--spacing-3);
            justify-content: flex-end;
        }

        /* 标签页系统 */
        .tabs-container {
            background: white;
            border-radius: var(--radius-lg);
            box-shadow: var(--shadow-md);
            overflow: hidden;
        }

        .tab-navigation {
            display: flex;
            border-bottom: 1px solid var(--color-border-primary);
            background: var(--color-bg-secondary);
        }

        .tab-button {
            flex: 1;
            padding: var(--spacing-4) var(--spacing-6);
            border: none;
            background: none;
            color: var(--color-text-secondary);
            font-weight: var(--font-weight-medium);
            cursor: pointer;
            transition: all var(--transition-fast) var(--ease-in-out);
            position: relative;
        }

        .tab-button:hover {
            background: var(--color-bg-tertiary);
            color: var(--color-text-primary);
        }

        .tab-button.active {
            color: #8b5cf6;
            background: white;
        }

        .tab-button.active::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 2px;
            background: #8b5cf6;
        }

        .tab-content {
            padding: var(--spacing-6);
            min-height: 600px;
        }

        .tab-panel {
            display: none;
        }

        .tab-panel.active {
            display: block;
        }

        /* 图表容器 */
        .chart-grid {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: var(--spacing-6);
            margin-bottom: var(--spacing-6);
        }

        .chart-container {
            background: white;
            border-radius: var(--radius-lg);
            padding: var(--spacing-6);
            box-shadow: var(--shadow-md);
            min-height: 400px;
        }

        .chart-title {
            font-size: var(--font-size-lg);
            font-weight: var(--font-weight-semibold);
            margin-bottom: var(--spacing-4);
            color: var(--color-text-primary);
        }

        .chart-canvas {
            width: 100%;
            height: 350px;
        }

        /* 情感卡片 */
        .sentiment-card {
            background: white;
            border-radius: var(--radius-lg);
            padding: var(--spacing-6);
            box-shadow: var(--shadow-md);
            margin-bottom: var(--spacing-4);
            border-left: 4px solid;
        }

        .sentiment-card.positive {
            border-left-color: var(--color-success);
        }

        .sentiment-card.negative {
            border-left-color: var(--color-error);
        }

        .sentiment-card.neutral {
            border-left-color: var(--color-info);
        }

        .sentiment-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: var(--spacing-3);
        }

        .sentiment-title {
            font-size: var(--font-size-lg);
            font-weight: var(--font-weight-semibold);
            color: var(--color-text-primary);
        }

        .sentiment-badge {
            padding: var(--spacing-1) var(--spacing-3);
            border-radius: var(--radius-full);
            font-size: var(--font-size-xs);
            font-weight: var(--font-weight-semibold);
            text-transform: uppercase;
        }

        .sentiment-badge.positive {
            background: var(--color-success-light);
            color: var(--color-success);
        }

        .sentiment-badge.negative {
            background: var(--color-error-light);
            color: var(--color-error);
        }

        .sentiment-badge.neutral {
            background: var(--color-info-light);
            color: var(--color-info);
        }

        .sentiment-content {
            color: var(--color-text-secondary);
            line-height: var(--line-height-relaxed);
            margin-bottom: var(--spacing-3);
        }

        .sentiment-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: var(--font-size-sm);
            color: var(--color-text-tertiary);
        }

        /* 关键词云 */
        .keyword-cloud {
            display: flex;
            flex-wrap: wrap;
            gap: var(--spacing-2);
            padding: var(--spacing-4);
            background: white;
            border-radius: var(--radius-lg);
            box-shadow: var(--shadow-md);
        }

        .keyword-tag {
            padding: var(--spacing-2) var(--spacing-3);
            border-radius: var(--radius-full);
            font-size: var(--font-size-sm);
            font-weight: var(--font-weight-medium);
            background: var(--color-bg-secondary);
            color: var(--color-text-primary);
            transition: all var(--transition-fast) var(--ease-in-out);
            cursor: pointer;
        }

        .keyword-tag:hover {
            background: #8b5cf6;
            color: white;
            transform: translateY(-1px);
        }

        .keyword-tag.positive {
            background: var(--color-success-light);
            color: var(--color-success);
        }

        .keyword-tag.negative {
            background: var(--color-error-light);
            color: var(--color-error);
        }

        .keyword-tag.neutral {
            background: var(--color-info-light);
            color: var(--color-info);
        }

        /* 情感趋势线 */
        .trend-legend {
            display: flex;
            gap: var(--spacing-4);
            justify-content: center;
            margin-bottom: var(--spacing-4);
        }

        .trend-item {
            display: flex;
            align-items: center;
            gap: var(--spacing-2);
            font-size: var(--font-size-sm);
        }

        .trend-color {
            width: 12px;
            height: 12px;
            border-radius: 50%;
        }

        .trend-color.positive {
            background: var(--color-success);
        }

        .trend-color.negative {
            background: var(--color-error);
        }

        .trend-color.neutral {
            background: var(--color-info);
        }

        /* 列表容器 */
        .list-container {
            background: white;
            border-radius: var(--radius-lg);
            padding: var(--spacing-6);
            box-shadow: var(--shadow-md);
        }

        .list-title {
            font-size: var(--font-size-lg);
            font-weight: var(--font-weight-semibold);
            margin-bottom: var(--spacing-4);
            color: var(--color-text-primary);
        }

        .list-item {
            padding: var(--spacing-3) 0;
            border-bottom: 1px solid var(--color-border-primary);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .list-item:last-child {
            border-bottom: none;
        }

        /* 情感指标 */
        .sentiment-indicator {
            display: inline-flex;
            align-items: center;
            gap: var(--spacing-2);
            padding: var(--spacing-2);
            border-radius: var(--radius);
            font-size: var(--font-size-sm);
            font-weight: var(--font-weight-medium);
        }

        .sentiment-indicator.positive {
            background: var(--color-success-light);
            color: var(--color-success);
        }

        .sentiment-indicator.negative {
            background: var(--color-error-light);
            color: var(--color-error);
        }

        .sentiment-indicator.neutral {
            background: var(--color-info-light);
            color: var(--color-info);
        }

        /* 加载状态 */
        .loading-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: var(--spacing-12);
            color: var(--color-text-secondary);
        }

        .loading-spinner {
            width: 48px;
            height: 48px;
            border: 4px solid var(--color-border-primary);
            border-top: 4px solid #8b5cf6;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: var(--spacing-4);
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* 空状态 */
        .empty-state {
            text-align: center;
            padding: var(--spacing-12);
            color: var(--color-text-secondary);
        }

        .empty-state-icon {
            font-size: 48px;
            margin-bottom: var(--spacing-4);
            opacity: 0.5;
        }

        .empty-state-title {
            font-size: var(--font-size-lg);
            font-weight: var(--font-weight-semibold);
            margin-bottom: var(--spacing-2);
        }

        .empty-state-description {
            color: var(--color-text-secondary);
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .content-area {
                padding: var(--spacing-4);
            }

            .chart-grid {
                grid-template-columns: 1fr;
            }

            .filter-grid {
                grid-template-columns: 1fr;
            }

            .filter-actions {
                flex-direction: column;
            }

            .tab-navigation {
                flex-wrap: wrap;
            }

            .tab-button {
                flex: 1 1 50%;
            }
        }

        @media (max-width: 480px) {
            .tab-button {
                flex: 1 1 100%;
            }

            .stats-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
{% endblock %}

{% block content %}
<div class="space-y-6 sentiment-page">
    <!-- 页面标题 -->
    <div class="page-header">
        <div>
            <h1 class="page-title">情感分析</h1>
            <p class="page-subtitle">深度分析信访记录中的情感倾向，洞察用户情绪变化趋势</p>
        </div>
    </div>

    <!-- 统计概览 -->
    <div class="stats-grid">
        <div class="stat-card-enhanced">
            <div class="stat-value" id="totalRecords">-</div>
            <div class="stat-label">总记录数</div>
        </div>

        <div class="stat-card-enhanced positive">
            <div class="stat-value" id="dominantSentiment">-</div>
            <div class="stat-label">主要情感</div>
        </div>

        <div class="stat-card-enhanced negative">
            <div class="stat-value" id="avgConfidence">-</div>
            <div class="stat-label">平均置信度</div>
        </div>

        <div class="stat-card-enhanced neutral">
            <div class="stat-value" id="totalKeywords">-</div>
            <div class="stat-label">关键词数</div>
        </div>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
        <h3 class="filter-title">分析筛选</h3>
        <div class="filter-grid">
            <div class="form-group">
                <label class="form-label">分析任务</label>
                <select class="form-select" id="taskSelect">
                    <option value="">全部任务</option>
                </select>
            </div>

            <div class="form-group">
                <label class="form-label">开始日期</label>
                <input type="date" class="form-control" id="startDate">
            </div>

            <div class="form-group">
                <label class="form-label">结束日期</label>
                <input type="date" class="form-control" id="endDate">
            </div>

            <div class="form-group">
                <label class="form-label">情感类型</label>
                <select class="form-select" id="sentimentType">
                    <option value="">全部情感</option>
                    <option value="positive">正面情感</option>
                    <option value="negative">负面情感</option>
                    <option value="neutral">中性情感</option>
                </select>
            </div>

            <div class="form-group">
                <label class="form-label">关键词过滤</label>
                <input type="text" class="form-control" id="keywordFilter" placeholder="输入关键词进行过滤">
            </div>

            <div class="form-group">
                <label class="form-label">最小置信度</label>
                <input type="number" class="form-control" id="minConfidence" min="0" max="1" step="0.1" placeholder="0.0">
            </div>
        </div>

        <div class="filter-actions">
            <button type="button" class="btn btn-secondary" onclick="resetFilters()">
                <i class="fas fa-undo"></i>
                重置筛选
            </button>
            <button type="button" class="btn btn-primary" onclick="loadAnalysis()">
                <i class="fas fa-search"></i>
                开始分析
            </button>
        </div>
    </div>

    <!-- 分析结果标签页 -->
    <div class="tabs-container">
        <div class="tab-navigation">
            <button class="tab-button active" onclick="switchTab('distribution')">
                <i class="fas fa-chart-pie"></i>
                情感分布
            </button>
            <button class="tab-button" onclick="switchTab('trends')">
                <i class="fas fa-chart-line"></i>
                情感趋势
            </button>
            <button class="tab-button" onclick="switchTab('keywords')">
                <i class="fas fa-tags"></i>
                关键词分析
            </button>
            <button class="tab-button" onclick="switchTab('confidence')">
                <i class="fas fa-tachometer-alt"></i>
                置信度分析
            </button>
            <button class="tab-button" onclick="switchTab('content')">
                <i class="fas fa-fire"></i>
                热门内容
            </button>
        </div>

        <div class="tab-content">
            <!-- 情感分布 -->
            <div id="distribution-tab" class="tab-panel active">
                <div class="chart-grid">
                    <div class="chart-container">
                        <h3 class="chart-title">情感分布图</h3>
                        <div id="sentimentDistributionChart" class="chart-canvas"></div>
                    </div>
                    <div class="list-container">
                        <h3 class="list-title">情感构成</h3>
                        <div id="sentimentBreakdown"></div>
                    </div>
                </div>
            </div>

            <!-- 情感趋势 -->
            <div id="trends-tab" class="tab-panel">
                <div class="chart-container">
                    <h3 class="chart-title">情感趋势分析</h3>
                    <div class="trend-legend">
                        <div class="trend-item">
                            <div class="trend-color positive"></div>
                            <span>正面情感</span>
                        </div>
                        <div class="trend-item">
                            <div class="trend-color negative"></div>
                            <span>负面情感</span>
                        </div>
                        <div class="trend-item">
                            <div class="trend-color neutral"></div>
                            <span>中性情感</span>
                        </div>
                    </div>
                    <div id="sentimentTrendsChart" class="chart-canvas"></div>
                </div>
            </div>

            <!-- 关键词分析 -->
            <div id="keywords-tab" class="tab-panel">
                <div class="chart-grid">
                    <div class="chart-container">
                        <h3 class="chart-title">关键词频率分析</h3>
                        <div id="keywordAnalysisChart" class="chart-canvas"></div>
                    </div>
                    <div class="list-container">
                        <h3 class="list-title">热门关键词</h3>
                        <div id="keywordRanking"></div>
                    </div>
                </div>
            </div>

            <!-- 置信度分析 -->
            <div id="confidence-tab" class="tab-panel">
                <div class="chart-grid">
                    <div class="chart-container">
                        <h3 class="chart-title">置信度统计</h3>
                        <div id="confidenceChart" class="chart-canvas"></div>
                    </div>
                    <div class="chart-container">
                        <h3 class="chart-title">置信度分布</h3>
                        <div id="confidenceDistributionChart" class="chart-canvas"></div>
                    </div>
                </div>
            </div>

            <!-- 热门内容 -->
            <div id="content-tab" class="tab-panel">
                <div id="popularContent"></div>
            </div>
        </div>
    </div>

    <!-- 加载遮罩 -->
    <div id="loadingOverlay" class="loading-overlay" style="display: none;">
        <div class="loading-container">
            <div class="loading-spinner"></div>
            <div class="loading-text">正在分析情感数据，请稍候...</div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<!-- 核心脚本 -->
<script src="/static/js/utils/ApiClient.js"></script>
<script src="/static/js/utils/CacheManager.js"></script>
<script src="/static/js/utils/ErrorHandler.js"></script>
<script src="/static/js/components/base/BaseComponent.js"></script>
<script src="/static/js/components/base/StatCard.js"></script>
<script src="/static/js/components/base/FilterPanel.js"></script>
<script src="/static/js/components/base/ChartContainer.js"></script>

<!-- ECharts 图表库 -->
<script src="/static/vendor/echarts/echarts.min.js"></script>

<!-- 页面逻辑 -->
<script>
    // 全局变量
    let charts = {};
    let currentData = null;
    let apiClient = null;
    let cacheManager = null;
    let errorHandler = null;

    // 页面初始化
    document.addEventListener('DOMContentLoaded', function() {
        initializeUtils();
        initializeComponents();
        setDefaultDates();
        loadTasks();
        setupEventListeners();
    });

    // 初始化工具类
    function initializeUtils() {
        apiClient = new ApiClient({
            baseURL: '/api',
            timeout: 30000,
            defaultHeaders: {
                'Content-Type': 'application/json'
            }
        });

        cacheManager = new CacheManager({
            prefix: 'sentiment_analysis_',
            defaultTTL: 300000, // 5分钟
            storage: 'localStorage'
        });

        errorHandler = new ErrorHandler({
            enableLogging: true,
            enableNotifications: true,
            notificationDuration: 5000
        });
    }

    // 初始化组件
    function initializeComponents() {
        // 初始化图表
        initializeCharts();

        // 设置响应式调整
        window.addEventListener('resize', debounce(() => {
            Object.values(charts).forEach(chart => {
                if (chart && chart.resize) {
                    chart.resize();
                }
            });
        }, 300));
    }

    // 设置默认日期
    function setDefaultDates() {
        const today = new Date();
        const thirtyDaysAgo = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000);

        document.getElementById('endDate').value = today.toISOString().split('T')[0];
        document.getElementById('startDate').value = thirtyDaysAgo.toISOString().split('T')[0];
    }

    // 设置事件监听器
    function setupEventListeners() {
        // 监听筛选条件变化
        ['taskSelect', 'startDate', 'endDate', 'sentimentType', 'keywordFilter', 'minConfidence'].forEach(id => {
            const element = document.getElementById(id);
            element.addEventListener('change', debounce(() => {
                // 可以添加自动筛选功能
            }, 500));
        });
    }

    // 加载分析任务
    async function loadTasks() {
        try {
            const cacheKey = 'analysis_tasks';
            const cachedData = cacheManager.get(cacheKey);

            if (cachedData) {
                populateTaskSelect(cachedData);
                return;
            }

            const response = await apiClient.get('/analysis-tasks', {
                params: {
                    status: 'completed',
                    limit: 100
                }
            });

            if (response.success) {
                const tasks = response.data.tasks || response.data.items || response.data || [];
                cacheManager.set(cacheKey, tasks, 300000); // 缓存5分钟
                populateTaskSelect(tasks);
            }
        } catch (error) {
            errorHandler.handleError(error, '加载分析任务失败');
        }
    }

    // 填充任务选择框
    function populateTaskSelect(tasks) {
        const taskSelect = document.getElementById('taskSelect');
        taskSelect.innerHTML = '<option value="">全部任务</option>';

        tasks.forEach(task => {
            const option = document.createElement('option');
            option.value = task.id;
            option.textContent = task.name || `任务 ${task.id}`;
            taskSelect.appendChild(option);
        });
    }

    // 切换标签页
    function switchTab(tabId) {
        // 更新标签按钮状态
        document.querySelectorAll('.tab-button').forEach(btn => {
            btn.classList.remove('active');
        });
        event.target.classList.add('active');

        // 更新标签内容
        document.querySelectorAll('.tab-panel').forEach(panel => {
            panel.classList.remove('active');
        });
        document.getElementById(`${tabId}-tab`).classList.add('active');

        // 重新调整图表大小
        setTimeout(() => {
            const activeCharts = getActiveCharts(tabId);
            activeCharts.forEach(chartId => {
                if (charts[chartId] && charts[chartId].resize) {
                    charts[chartId].resize();
                }
            });
        }, 100);
    }

    // 获取当前标签页的图表
    function getActiveCharts(tabId) {
        const chartMap = {
            'distribution': ['sentimentDistribution'],
            'trends': ['sentimentTrends'],
            'keywords': ['keywordAnalysis'],
            'confidence': ['confidence', 'confidenceDistribution'],
            'content': []
        };
        return chartMap[tabId] || [];
    }

    // 加载分析数据
    async function loadAnalysis() {
        const loadingOverlay = document.getElementById('loadingOverlay');
        loadingOverlay.style.display = 'flex';

        try {
            const filters = getFilters();
            const cacheKey = `sentiment_analysis_${JSON.stringify(filters)}`;

            // 检查缓存
            const cachedData = cacheManager.get(cacheKey);
            if (cachedData) {
                updateAnalysisData(cachedData);
                return;
            }

            // 发起分析请求
            const response = await apiClient.post('/sentiment-analysis/analyze', filters);

            if (response.success) {
                currentData = response.data;
                cacheManager.set(cacheKey, response.data, 600000); // 缓存10分钟
                updateAnalysisData(response.data);

                // 显示成功消息
                errorHandler.showNotification('情感分析完成', 'success');
            } else {
                throw new Error(response.message || '分析失败');
            }
        } catch (error) {
            errorHandler.handleError(error, '情感分析失败');
            showEmptyState();
        } finally {
            loadingOverlay.style.display = 'none';
        }
    }

    // 获取筛选条件
    function getFilters() {
        return {
            task_id: document.getElementById('taskSelect').value ? parseInt(document.getElementById('taskSelect').value) : null,
            start_date: document.getElementById('startDate').value || null,
            end_date: document.getElementById('endDate').value || null,
            sentiment_type: document.getElementById('sentimentType').value || null,
            keyword_filter: document.getElementById('keywordFilter').value || null,
            min_confidence: document.getElementById('minConfidence').value ? parseFloat(document.getElementById('minConfidence').value) : null
        };
    }

    // 更新分析数据
    function updateAnalysisData(data) {
        // 更新统计概览
        updateDashboard(data);

        // 更新所有图表
        updateAllCharts(data);
    }

    // 更新仪表板
    function updateDashboard(data) {
        const metadata = data.analysis_metadata || {};
        const distribution = data.sentiment_distribution || {};
        const keywordAnalysis = data.keyword_analysis || {};

        document.getElementById('totalRecords').textContent = (metadata.total_records || 0).toLocaleString();
        document.getElementById('dominantSentiment').textContent = getSentimentLabel(distribution.dominant_sentiment || 'neutral');
        document.getElementById('avgConfidence').textContent = (metadata.average_confidence || 0).toFixed(3);
        document.getElementById('totalKeywords').textContent = Object.keys(keywordAnalysis.keyword_frequencies || {}).length.toLocaleString();
    }

    // 更新所有图表
    function updateAllCharts(data) {
        updateSentimentDistributionChart(data.sentiment_distribution || {});
        updateSentimentTrendsChart(data.sentiment_trends || {});
        updateKeywordAnalysisChart(data.keyword_analysis || {});
        updateConfidenceChart(data.confidence_analysis || {});
        updateConfidenceDistributionChart(data.confidence_analysis || {});
        updatePopularContent(data.popular_sentiments || []);
        updateSentimentBreakdown(data.sentiment_distribution || {});
        updateKeywordRanking(data.keyword_analysis || {});
    }

    // 初始化图表
    function initializeCharts() {
        charts.sentimentDistribution = echarts.init(document.getElementById('sentimentDistributionChart'));
        charts.sentimentTrends = echarts.init(document.getElementById('sentimentTrendsChart'));
        charts.keywordAnalysis = echarts.init(document.getElementById('keywordAnalysisChart'));
        charts.confidence = echarts.init(document.getElementById('confidenceChart'));
        charts.confidenceDistribution = echarts.init(document.getElementById('confidenceDistributionChart'));
    }

    // 更新情感分布图表
    function updateSentimentDistributionChart(data) {
        const types = data.types || [];
        const counts = data.counts || [];

        const option = {
            title: {
                text: '情感分布',
                left: 'center',
                textStyle: {
                    fontSize: 18,
                    fontWeight: 'bold'
                }
            },
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                type: 'scroll',
                orient: 'vertical',
                right: 10,
                top: 20,
                bottom: 20,
                textStyle: {
                    fontSize: 12
                }
            },
            series: [{
                name: '情感类型',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: 20,
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: types.map((type, index) => ({
                    value: counts[index] || 0,
                    name: getSentimentLabel(type),
                    itemStyle: {
                        color: getSentimentColor(type)
                    }
                }))
            }]
        };

        charts.sentimentDistribution.setOption(option);
    }

    // 更新情感趋势图表
    function updateSentimentTrendsChart(data) {
        const dates = data.time_series?.map(item => item.date) || [];
        const sentimentTypes = data.sentiment_types || [];

        const series = sentimentTypes.map(type => ({
            name: getSentimentLabel(type),
            type: 'line',
            smooth: true,
            data: data.time_series?.map(item => item[type] || 0) || [],
            itemStyle: {
                color: getSentimentColor(type)
            },
            areaStyle: {
                opacity: 0.1
            }
        }));

        const option = {
            title: {
                text: '情感趋势变化',
                left: 'center',
                textStyle: {
                    fontSize: 18,
                    fontWeight: 'bold'
                }
            },
            tooltip: {
                trigger: 'axis',
                formatter: '{b}<br/>{a}: {c}'
            },
            legend: {
                data: sentimentTypes.map(type => getSentimentLabel(type)),
                top: 30,
                textStyle: {
                    fontSize: 12
                }
            },
            xAxis: {
                type: 'category',
                data: dates,
                axisLabel: {
                    fontSize: 12,
                    rotate: 45
                }
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    fontSize: 12
                }
            },
            series: series
        };

        charts.sentimentTrends.setOption(option);
    }

    // 更新关键词分析图表
    function updateKeywordAnalysisChart(data) {
        const keywordFrequencies = data.keyword_frequencies || {};
        const keywords = Object.keys(keywordFrequencies).slice(0, 15);
        const frequencies = keywords.map(keyword => keywordFrequencies[keyword]);

        const option = {
            title: {
                text: '关键词频率分析',
                left: 'center',
                textStyle: {
                    fontSize: 18,
                    fontWeight: 'bold'
                }
            },
            tooltip: {
                trigger: 'axis',
                formatter: '{b}<br/>频率: {c}'
            },
            xAxis: {
                type: 'category',
                data: keywords,
                axisLabel: {
                    fontSize: 12,
                    rotate: 45
                }
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    fontSize: 12
                }
            },
            series: [{
                data: frequencies,
                type: 'bar',
                itemStyle: {
                    color: '#8b5cf6'
                }
            }]
        };

        charts.keywordAnalysis.setOption(option);
    }

    // 更新置信度图表
    function updateConfidenceChart(data) {
        const option = {
            title: {
                text: '置信度统计',
                left: 'center',
                textStyle: {
                    fontSize: 18,
                    fontWeight: 'bold'
                }
            },
            tooltip: {
                trigger: 'axis',
                formatter: '{b}: {c}'
            },
            xAxis: {
                type: 'category',
                data: ['平均置信度', '最低置信度', '最高置信度'],
                axisLabel: {
                    fontSize: 12
                }
            },
            yAxis: {
                type: 'value',
                min: 0,
                max: 1,
                axisLabel: {
                    formatter: '{0:.2f}'
                }
            },
            series: [{
                data: [
                    data.average_confidence || 0,
                    data.min_confidence || 0,
                    data.max_confidence || 0
                ],
                type: 'bar',
                itemStyle: {
                    color: function(params) {
                        const colors = ['#10b981', '#ef4444', '#3b82f6'];
                        return colors[params.dataIndex];
                    }
                }
            }]
        };

        charts.confidence.setOption(option);
    }

    // 更新置信度分布图表
    function updateConfidenceDistributionChart(data) {
        const distribution = data.distribution || {};
        const categories = Object.keys(distribution);
        const values = Object.values(distribution);

        const option = {
            title: {
                text: '置信度分布',
                left: 'center',
                textStyle: {
                    fontSize: 18,
                    fontWeight: 'bold'
                }
            },
            tooltip: {
                trigger: 'axis',
                formatter: '{b}: {c}'
            },
            xAxis: {
                type: 'category',
                data: categories,
                axisLabel: {
                    fontSize: 12
                }
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    fontSize: 12
                }
            },
            series: [{
                data: values,
                type: 'bar',
                itemStyle: {
                    color: function(params) {
                        const colors = ['#10b981', '#f59e0b', '#ef4444', '#6b7280'];
                        return colors[params.dataIndex];
                    }
                }
            }]
        };

        charts.confidenceDistribution.setOption(option);
    }

    // 更新热门内容
    function updatePopularContent(data) {
        const content = document.getElementById('popularContent');

        if (!data || data.length === 0) {
            content.innerHTML = '<div class="empty-state"><i class="fas fa-comments empty-state-icon"></i><h3 class="empty-state-title">暂无热门内容</h3><p class="empty-state-description">当前筛选条件下没有找到热门情感内容</p></div>';
            return;
        }

        let html = '';
        data.forEach(item => {
            const sentimentType = item.sentiment_type || 'neutral';
            const sentimentClass = sentimentType;

            html += `
                    <div class="sentiment-card ${sentimentClass}">
                        <div class="sentiment-header">
                            <div class="sentiment-title">情感内容</div>
                            <div class="sentiment-badge ${sentimentClass}">${getSentimentLabel(sentimentType)}</div>
                        </div>
                        <div class="sentiment-content">
                            ${item.summary || '无摘要内容'}
                        </div>
                        <div class="sentiment-meta">
                            <span><i class="fas fa-calendar"></i> ${item.created_at || '未知时间'}</span>
                            <span><i class="fas fa-percentage"></i> 置信度: ${((item.confidence || 0) * 100).toFixed(1)}%</span>
                            <span><i class="fas fa-tags"></i> ${item.keywords || '无关键词'}</span>
                        </div>
                    </div>
                `;
        });

        content.innerHTML = html;
    }

    // 更新情感构成
    function updateSentimentBreakdown(data) {
        const content = document.getElementById('sentimentBreakdown');
        const types = data.types || [];
        const counts = data.counts || [];
        const percentages = data.percentages || [];

        if (types.length === 0) {
            content.innerHTML = '<div class="empty-state"><p>暂无情感分布数据</p></div>';
            return;
        }

        let html = '';
        types.forEach((type, index) => {
            const percentage = percentages[index] || 0;
            const count = counts[index] || 0;
            const sentimentClass = type;

            html += `
                    <div class="list-item">
                        <div class="list-item-content">
                            <div class="list-item-title">
                                ${getSentimentLabel(type)}
                            </div>
                        </div>
                        <div class="list-item-value">
                            <div class="list-item-count">${count}</div>
                            <div class="sentiment-indicator ${sentimentClass}">${percentage}%</div>
                        </div>
                    </div>
                `;
        });

        content.innerHTML = html;
    }

    // 更新关键词排行
    function updateKeywordRanking(data) {
        const content = document.getElementById('keywordRanking');
        const keywordFrequencies = data.keyword_frequencies || {};
        const keywords = Object.keys(keywordFrequencies).slice(0, 10);

        if (keywords.length === 0) {
            content.innerHTML = '<div class="empty-state"><p>暂无关键词数据</p></div>';
            return;
        }

        let html = '';
        keywords.forEach((keyword, index) => {
            const frequency = keywordFrequencies[keyword];

            html += `
                    <div class="list-item">
                        <div class="list-item-content">
                            <div class="list-item-title">${index + 1}. ${keyword}</div>
                        </div>
                        <div class="list-item-value">
                            <div class="list-item-count">${frequency}</div>
                        </div>
                    </div>
                `;
        });

        content.innerHTML = html;
    }

    // 获取情感标签
    function getSentimentLabel(type) {
        const labels = {
            'positive': '正面情感',
            'negative': '负面情感',
            'neutral': '中性情感'
        };
        return labels[type] || type;
    }

    // 获取情感颜色
    function getSentimentColor(type) {
        const colors = {
            'positive': '#10b981',
            'negative': '#ef4444',
            'neutral': '#6b7280'
        };
        return colors[type] || '#6b7280';
    }

    // 重置筛选条件
    function resetFilters() {
        document.getElementById('taskSelect').value = '';
        document.getElementById('sentimentType').value = '';
        document.getElementById('keywordFilter').value = '';
        document.getElementById('minConfidence').value = '';
        setDefaultDates();

        // 显示重置成功消息
        errorHandler.showNotification('筛选条件已重置', 'info');
    }

    // 显示空状态
    function showEmptyState() {
        // 在各个标签页中显示空状态
        ['distribution', 'trends', 'keywords', 'confidence', 'content'].forEach(tabId => {
            const panel = document.getElementById(`${tabId}-tab`);
            const emptyHtml = '<div class="empty-state"><i class="fas fa-chart-bar empty-state-icon"></i><h3 class="empty-state-title">暂无分析数据</h3><p class="empty-state-description">请调整筛选条件后重新分析</p></div>';

            // 保留图表容器，显示空状态
            const chartContainers = panel.querySelectorAll('.chart-canvas');
            chartContainers.forEach(container => {
                container.innerHTML = emptyHtml;
            });

            const listContainers = panel.querySelectorAll('[id$="Breakdown"], [id$="Ranking"], [id$="Content"]');
            listContainers.forEach(container => {
                container.innerHTML = emptyHtml;
            });
        });
    }

    // 工具函数：防抖
    function debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    // 页面卸载时清理资源
    window.addEventListener('beforeunload', function() {
        // 清理图表实例
        Object.values(charts).forEach(chart => {
            if (chart && chart.dispose) {
                chart.dispose();
            }
        });

        // 清理缓存
        if (cacheManager) {
            cacheManager.clear();
        }
    });
</script>
{% endblock %}